// src/components/SystemOperations/SystemMonitor.jsx
import React, { useState, useEffect } from 'react';
import {
  Card, Row, Col, Statistic, Alert, Tabs, Progress
} from 'antd';
import {
  DashboardOutlined,
  DatabaseOutlined,
  HddOutlined,
  WarningOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';

const SystemMonitor = () => {
  const [stats, setStats] = useState(null);
  const [warnings, setWarnings] = useState([]);
  const [historyData, setHistoryData] = useState([]);

  // 模拟系统状态数据
  const mockStats = {
    cpuPercent: 45,
    memory: {
      total: 16,
      used: 8.5,
      available: 7.5,
      percent: 53.1
    },
    disk: {
      total: 512,
      used: 210,
      free: 302,
      percent: 41.0
    },
    network: {
      bytesSent: 123456789,
      bytesRecv: 987654321,
      packetsSent: 123456,
      packetsRecv: 654321
    },
    bootTime: '2025-09-01 08:30:15',
    timestamp: new Date().toLocaleString()
  };

  const fetchSystemStats = () => {
    // 模拟API调用
    const newStats = {
      ...mockStats,
      cpuPercent: Math.floor(Math.random() * 30) + 30, // 随机CPU使用率 30-60%
      memory: {
        ...mockStats.memory,
        percent: Math.floor(Math.random() * 20) + 45 // 随机内存使用率 45-65%
      }
    };

    setStats(newStats);

    // 模拟警告
    const newWarnings = [];
    if (newStats.cpuPercent > 85) {
      newWarnings.push(`CPU使用率过高: ${newStats.cpuPercent}%`);
    }

    if (newStats.memory.percent > 90) {
      newWarnings.push(`内存使用率过高: ${newStats.memory.percent}%`);
    }

    setWarnings(newWarnings);

    // 保存历史数据用于图表显示（保留最近20条）
    setHistoryData(prev => {
      const newData = [...prev, {
        time: new Date().toLocaleTimeString(),
        cpu: newStats.cpuPercent,
        memory: newStats.memory.percent,
        disk: newStats.disk.percent
      }];

      return newData.length > 20 ? newData.slice(-20) : newData;
    });
  };

  useEffect(() => {
    fetchSystemStats();
    const interval = setInterval(fetchSystemStats, 5000); // 5秒更新一次

    return () => clearInterval(interval);
  }, []);

  const getCpuChartOption = () => {
    return {
      title: { text: 'CPU使用率趋势' },
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: historyData.map(item => item.time),
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value} %'
        }
      },
      series: [{
        data: historyData.map(item => item.cpu),
        type: 'line',
        smooth: true,
        areaStyle: {},
        lineStyle: { color: '#1890ff' },
        itemStyle: { color: '#1890ff' }
      }]
    };
  };

  const getMemoryChartOption = () => {
    return {
      title: { text: '内存使用率趋势' },
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: historyData.map(item => item.time),
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value} %'
        }
      },
      series: [{
        data: historyData.map(item => item.memory),
        type: 'line',
        smooth: true,
        areaStyle: {},
        lineStyle: { color: '#52c41a' },
        itemStyle: { color: '#52c41a' }
      }]
    };
  };

  if (!stats) {
    return <div>加载中...</div>;
  }

  return (
    <div>
      {warnings.length > 0 && (
        <Alert
          message="系统警告"
          description={
            <ul style={{ margin: 0 }}>
              {warnings.map((warning, index) => (
                <li key={index}>{warning}</li>
              ))}
            </ul>
          }
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      <Row gutter={16}>
        <Col span={6}>
          <Card>
            <Statistic
              title="CPU使用率"
              value={stats.cpuPercent}
              suffix="%"
              valueStyle={{ color: stats.cpuPercent > 85 ? '#cf1322' : '#3f8600' }}
              prefix={<DashboardOutlined />}
            />
            <Progress
              percent={stats.cpuPercent}
              status={stats.cpuPercent > 85 ? 'exception' : 'normal'}
              strokeColor={stats.cpuPercent > 85 ? '#ff4d4f' : '#1890ff'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="内存使用率"
              value={stats.memory.percent}
              suffix="%"
              valueStyle={{ color: stats.memory.percent > 90 ? '#cf1322' : '#3f8600' }}
              prefix={<DatabaseOutlined />}
            />
            <Progress
              percent={stats.memory.percent}
              status={stats.memory.percent > 90 ? 'exception' : 'normal'}
              strokeColor={stats.memory.percent > 90 ? '#ff4d4f' : '#52c41a'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="磁盘使用率"
              value={stats.disk.percent}
              suffix="%"
              valueStyle={{ color: stats.disk.percent > 85 ? '#cf1322' : '#3f8600' }}
              prefix={<HddOutlined />}
            />
            <Progress
              percent={stats.disk.percent}
              status={stats.disk.percent > 85 ? 'exception' : 'normal'}
              strokeColor={stats.disk.percent > 85 ? '#ff4d4f' : '#722ed1'}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="系统运行时间"
              value={stats.bootTime}
              valueStyle={{ fontSize: '14px' }}
            />
          </Card>
        </Col>
      </Row>

      <Card style={{ marginTop: 16 }}>
        <Tabs defaultActiveKey="cpu">
          <Tabs.TabPane tab="CPU监控" key="cpu">
            <ReactECharts option={getCpuChartOption()} style={{ height: 300 }} />
          </Tabs.TabPane>
          <Tabs.TabPane tab="内存监控" key="memory">
            <ReactECharts option={getMemoryChartOption()} style={{ height: 300 }} />
          </Tabs.TabPane>
          <Tabs.TabPane tab="详细信息" key="detail">
            <Row gutter={16}>
              <Col span={12}>
                <h4>内存信息</h4>
                <p>总量: {stats.memory.total} GB</p>
                <p>已用: {stats.memory.used} GB</p>
                <p>可用: {stats.memory.available} GB</p>
              </Col>
              <Col span={12}>
                <h4>磁盘信息</h4>
                <p>总量: {stats.disk.total} GB</p>
                <p>已用: {stats.disk.used} GB</p>
                <p>剩余: {stats.disk.free} GB</p>
              </Col>
            </Row>
            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={12}>
                <h4>网络信息</h4>
                <p>发送: {(stats.network.bytesSent / (1024 ** 2)).toFixed(2)} MB</p>
                <p>接收: {(stats.network.bytesRecv / (1024 ** 2)).toFixed(2)} MB</p>
              </Col>
            </Row>
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default SystemMonitor;
